package com.aloda.task;

import com.aloda.cache.RedisUtils;
import com.aloda.constant.RedisConstant;
import com.aloda.entity.PageRecord;
import com.aloda.enums.RecordCategory;
import com.aloda.mapper.PageRecordMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class PageRecordTask {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private PageRecordMapper pageRecordMapper;

    @Scheduled(cron = "0 0 0 * * ?")//每天夜晚0点触发一次
    public void savePageView() {
        long dailyPV = redisUtils.getDailyPV();
        log.info("保存PV:{}", dailyPV);
        PageRecord pageRecord = new PageRecord();
        pageRecord.setCategory(RecordCategory.PV);
        pageRecord.setNums(dailyPV);
        pageRecord.setCreateTime(LocalDateTime.now());
        pageRecordMapper.insert(pageRecord);
        redisUtils.delete(RedisConstant.PV_KEY);
    }

    @Scheduled(cron = "0 0 0 * * ?")//每天夜晚0点触发一次
    public void saveUniqueVisitor() {
        long dailyUV = redisUtils.getDailyUV();
        log.info("保存UV:{}",dailyUV);
        PageRecord pageRecord = new PageRecord();
        pageRecord.setCategory(RecordCategory.UV);
        pageRecord.setNums(dailyUV);
        pageRecord.setCreateTime(LocalDateTime.now());
        pageRecordMapper.insert(pageRecord);
        redisUtils.delete(RedisConstant.UV_KEY);
    }
}
